package com.umeox.moto.watch.fitness.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.database.ContentObserver
import android.os.Bundle
import android.os.Handler
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.fitness.R
import com.umeox.moto.watch.fitness.adapter.ChallengeAdapter
import com.umeox.moto.watch.fitness.base.GlideApp
import com.umeox.moto.watch.fitness.data.PedometerContract
import com.umeox.moto.watch.fitness.data.PedometerPresenter
import com.umeox.moto.watch.fitness.db.AppDatabase
import com.umeox.moto.watch.fitness.db.model.TodayChallenge
import com.umeox.moto.watch.fitness.utils.StepManager
import com.umeox.moto.watch.fitness.utils.StepUtils
import com.umeox.moto.watch.fitness.utils.Utils
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.moto.watch.themes.widget.ProgressView
import com.umeox.moto.watch.themes.widget.RoundedImageView
import com.umeox.watch.moto.dataservice.DataProvider
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.text.NumberFormat
import java.util.*
import kotlin.math.max

class MainActivity : ThemeAppCompatActivity(), ChallengeAdapter.OnItemClickListener,
    PedometerContract.View,
    StepManager.OnPedometerRegisteredListener {

    private lateinit var mChallengeRv: RecyclerView
    private lateinit var challengeAdapter: ChallengeAdapter
    private var mChallengeList: MutableList<TodayChallenge>? = null
    private lateinit var mAvatar: RoundedImageView
    private lateinit var mStepProgressView: ProgressView
    private lateinit var mChallengeTotalRewardsTv: TextView
    private lateinit var mStepTv: TextView
    private lateinit var mDistanceTv: TextView
    private lateinit var mCaloriesTv: TextView

    private lateinit var mDataLL: LinearLayout

    private var mDistanceUnit = 0
    var mHandler = Handler()
    private var mAccountHeight = 0.0
    private var mAccountWeight = 0.0
    private val decimalFormat = DecimalFormat("#.##", DecimalFormatSymbols(Locale.ROOT))

    private var mStepTarget = 5000
    private var todayStepCount: Int = 0


    private var mPresenter: PedometerContract.Presenter? = null

    private lateinit var sportChallengeObserver: ContentObserver

    private var baseStep: Int = 0

    init {
        mPresenter = PedometerPresenter(this)
    }


    private fun registerObserver() {
        //监听联系人数据的监听对象
        sportChallengeObserver = object : ContentObserver(mHandler) {
            override fun onChange(selfChange: Boolean) {
                Logger.d("运动挑战数据发生改变")
                mChallengeList = AppDatabase.get().todayChallengeDao().loadAllChallenge()
                challengeAdapter.dataList = mChallengeList
            }
        }
        //监听运动挑战数据是否有变化
        DataProvider.SportsChallengeProvider.registerContentObserver(false, sportChallengeObserver)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        baseStep = intent.getIntExtra("cache_step",0)
        Logger.e("baseStep=$baseStep")

        initView()
        initData()
        mPresenter?.getStepInfo()

        registerObserver()
    }

    private fun initView() {
        mChallengeRv = findViewById(R.id.rv_challenge)
        mAvatar = findViewById(R.id.iv_avatar)
        mStepProgressView = findViewById(R.id.step_progress)
        mChallengeTotalRewardsTv = findViewById(R.id.tv_total_rewards)
        mStepTv = findViewById(R.id.tv_step)
        mDistanceTv = findViewById(R.id.tv_distances)
        mCaloriesTv = findViewById(R.id.tv_calories)
        mDataLL = findViewById(R.id.data_ll)

        mDistanceUnit = DataProvider.getDistanceUnit()
        mAccountHeight = DataProvider.getHeight()
        mAccountWeight = DataProvider.getWeight()
        mPresenter?.onCreate()
        StepManager.getInstance().setOnPedometerRegisteredListener(this)

        mChallengeTotalRewardsTv.text = DataProvider.getSportsChallengeRewardsValue().toString()

        val holderAvatar = DataProvider.getAvatar()
        if (holderAvatar.isNotEmpty()) {
            GlideApp.with(mContext)
                .load(holderAvatar)
                .centerCrop().into(mAvatar)
        }

        if(baseStep > 0){
            todayStepCount = baseStep;
            updateUI()
        }

    }

    private fun initData() {
        mChallengeList = mutableListOf()
        mChallengeList = AppDatabase.get().todayChallengeDao().loadAllChallenge()
        challengeAdapter = ChallengeAdapter(this, mChallengeList)
        challengeAdapter.setOnItemClickListener(this)

        mChallengeRv.layoutManager = object : LinearLayoutManager(this) {
            //解决RecyclerView嵌套RecyclerView滑动卡顿的问题
            //如果你的RecyclerView是水平滑动的话可以重写canScrollHorizontally方法
            override fun canScrollVertically() = false
        }
        //解决数据加载不完的问题
        mChallengeRv.isNestedScrollingEnabled = false
        mChallengeRv.setHasFixedSize(true)
        //解决数据加载完成后, 没有停留在顶部的问题
        mChallengeRv.isFocusable = false
        mChallengeRv.adapter = challengeAdapter


    }

    override fun onItemClick(challengeBean: TodayChallenge) {
        val intent = Intent(this@MainActivity, ChallengeTipActivity::class.java)
        val mBundle = Bundle()
        mBundle.putLong(Utils.EXTRA_KEY_ID, challengeBean.id)
        mBundle.putBoolean(Utils.EXTRA_KEY_AUTO, false)
        intent.putExtras(mBundle)
        startActivity(intent)

    }

    override fun onStepCountChange(stepCounts: Int) {
        todayStepCount = stepCounts + baseStep
        updateUI()
    }

    override fun onStepInfoChange(stepTarget: Int) {
        mStepTarget = stepTarget
        updateUI()
    }

    override fun onHolderInfoChange() {
        mAccountHeight = DataProvider.getHeight()
        mAccountWeight = DataProvider.getWeight()
        setDistanceCalories()
        mChallengeTotalRewardsTv.text = DataProvider.getSportsChallengeRewardsValue().toString()
    }

    override fun onDistanceUnitChange() {
        mDistanceUnit = DataProvider.getDistanceUnit()
        setDistanceCalories()
    }

    override fun onRegistered() {
        mPresenter?.start()
    }

    override fun onResume() {
        super.onResume()
        mPresenter?.start()
    }

    override fun onPause() {
        super.onPause()
        mPresenter?.stop(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        //mPresenter!!.onDestroy()
        StepManager.getInstance().setOnPedometerRegisteredListener(null)

        try {
            contentResolver.unregisterContentObserver(sportChallengeObserver)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun updateUI() {
        val percent = todayStepCount.toFloat() / mStepTarget
        val nf: NumberFormat = DecimalFormat("#,###", DecimalFormatSymbols(Locale.ROOT))
        val str = nf.format(todayStepCount.toLong())
        mStepTv.text = str
        mStepProgressView.progress = percent
        setDistanceCalories()
    }

    @SuppressLint("SetTextI18n")
    private fun setDistanceCalories() {
        val stepDistance: Double = StepUtils.getDistance(mAccountHeight).toDouble()
        val distance: Double = stepDistance * todayStepCount
        val calories: Double = StepUtils.getKcal(
            mAccountWeight,
            distance / 100 / 1000
        )
        mCaloriesTv.text = calories.toString()
        val distanceUnits = resources.getStringArray(R.array.Fitness_Unit_Distance)
        val v = distance / if (mDistanceUnit == 1) 100000 else 160900
        val distanceValue = if (todayStepCount == 0) 0 else max(v, 0.01)
        mDistanceTv.text = decimalFormat.format(distanceValue)
    }
}